package com.anyi.gulimall.product.service.impl;

import com.anyi.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.anyi.gulimall.product.dao.AttrGroupDao;
import com.anyi.gulimall.product.dao.CategoryDao;
import com.anyi.gulimall.product.entity.*;
import com.anyi.gulimall.product.service.AttrAttrgroupRelationService;
import com.anyi.gulimall.product.service.AttrGroupService;
import com.anyi.gulimall.product.service.ProductAttrValueService;
import com.anyi.gulimall.product.vo.AttrRespVo;
import com.anyi.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.anyi.gulimall.common.utils.PageUtils;
import com.anyi.gulimall.common.utils.Query;

import com.anyi.gulimall.product.dao.AttrDao;
import com.anyi.gulimall.product.service.AttrService;
import org.springframework.util.StringUtils;

import javax.jws.Oneway;
import javax.lang.model.type.ArrayType;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;


    @Autowired
    private AttrGroupServiceImpl attrGroupService;

    @Autowired
    private ProductAttrValueService productAttrValueService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 根据id分页查询数据
     * @param params
     * @param categoryId
     * @return
     */
    @Override
    public PageUtils queryArrtPage(Map<String, Object> params, Long categoryId,String attrType) {
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>().eq(AttrEntity::getAttrType,attrType.equalsIgnoreCase("base")?0:1);
        if(categoryId != 0){
            wrapper.eq(AttrEntity::getCatelogId,categoryId);
        }
        String  key = (String) params.get("key");
        // 条件查询
        if(!StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq(AttrEntity::getAttrId,key).or().like(AttrEntity::getAttrName,key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        // 封装返回信息
        List<AttrEntity> records = page.getRecords();
        List<AttrVo> collect = records.stream().map(item -> {
            AttrRespVo attrVo = new AttrRespVo();
            BeanUtils.copyProperties(item, attrVo);

            // 设置分类属性相关信息
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, item.getAttrId()));
            if(relationEntity !=null){
                attrVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroup = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroup !=null){
                    attrVo.setGroupName(attrGroup.getAttrGroupName());
                }
            }


            // 设置分类信息
            CategoryEntity categoryEntity = categoryDao.selectById(item.getCatelogId());

            if (categoryEntity !=null){
                attrVo.setCatelogName(categoryEntity.getName());
            }
            return attrVo;
        }).collect(Collectors.toList());

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(collect);

        return  pageUtils;
    }

    /**
     * 保存属性信息
     * @param attrVo
     */
    @Override
    public void saveAttr(AttrVo attrVo) {
        // 保存自己基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);
        // 保存所属分组信息
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attrVo.getAttrGroupId());
        relationEntity.setAttrId(attrEntity.getAttrId());

        relationDao.insert(relationEntity);
    }

    /**
     * 根据attrId获取详细信息
     * @param attrId
     * @return
     */
    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        //设置组信息
        AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
        if (relationEntity !=null){
            attrRespVo.setAttrGroupId(relationEntity.getAttrGroupId());
            AttrGroupEntity attrGroup = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if (attrGroup !=null){
                attrRespVo.setGroupName(attrGroup.getAttrGroupName());
            }
        }
        //设置分类信息
        List<Long> attrPaths = attrGroupService.getAttrPaths(attrEntity.getCatelogId(), new ArrayList<>());
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if(categoryEntity!=null){
            Collections.reverse(attrPaths);
            attrRespVo.setCatelogPath(attrPaths.toArray(new Long[attrPaths.size()]));
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    /**
     * 更新属性系信息
     * @param attr
     */
    @Override
    public void updateAttrEntity(AttrVo attr) {
        // 保存自己基本信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);
        // 保存所属分组信息
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        relationEntity.setAttrGroupId(attr.getAttrGroupId());
        relationEntity.setAttrId(attrEntity.getAttrId());
        attrAttrgroupRelationService.saveOrUpdate(relationEntity,new LambdaUpdateWrapper<AttrAttrgroupRelationEntity>().eq(AttrAttrgroupRelationEntity::getAttrId,attrEntity.getAttrId()));
    }

    /**
     * 根据spuId 查询出所有属性信息
     * @param spuId
     * @return
     */
    @Override
    public List<ProductAttrValueEntity> getListForSpu(Long spuId) {
        LambdaQueryWrapper<ProductAttrValueEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ProductAttrValueEntity::getSpuId,spuId);
        List<ProductAttrValueEntity> list = productAttrValueService.list(wrapper);
        return list;
    }

    /**
     * 根据spuId 更新属性信息
     * @param spuId
     * @param list
     */
    @Override
    public void updateSpuAttr(Long spuId, List<ProductAttrValueEntity> list) {
        List<ProductAttrValueEntity> collect = list.stream().map(item -> {
            item.setSpuId(spuId);
            return item;
        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        List<Long> collect = this.list(new LambdaQueryWrapper<AttrEntity>().in(AttrEntity::getAttrId, attrIds)).stream().filter(
                item -> item.getSearchType() == 1
        ).map(item -> item.getAttrId()).collect(Collectors.toList());
        return collect;
    }


}